package ca.intelliware.commons.virtualization.vmware;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import ca.intelliware.commons.virtualization.DataCenter;
import ca.intelliware.commons.virtualization.Host;
import ca.intelliware.commons.virtualization.VMachine;

import com.vmware.vim25.mo.ComputeResource;
import com.vmware.vim25.mo.Datacenter;
import com.vmware.vim25.mo.HostSystem;
import com.vmware.vim25.mo.ManagedObject;

public class VmDataCenter implements DataCenter {
	private Datacenter datacenter;
	
	VmDataCenter(Datacenter datacenter) throws Exception {
		this.datacenter = datacenter;
	}

	public String getId() {
		return datacenter.getName();
	}

	public Host host(String id) throws IOException {
		Host foundHost = null;
		for (Host vmHost : hosts()) {
			if (vmHost.getId().equalsIgnoreCase(id)) {
				foundHost = vmHost;
				break;
			}
		}
		return foundHost;
	}

	@Override
	public List<Host> hosts() throws IOException {
			ArrayList<ManagedObject> computeResourceManagedObjects = VmwareVmExplorer
					.findManagedObjectsByType(this.datacenter.getHostFolder()
							.getChildEntity(), "ComputeResource");
			List<Host> hosts = new ArrayList<Host>();
			for (ManagedObject computeResource : computeResourceManagedObjects) {
				HostSystem[] hostSystems = ((ComputeResource) computeResource)
						.getHosts();
				for (HostSystem hostSystem : hostSystems) {
					hosts.add(new VmHost(hostSystem));
				}
			}
			return hosts;
	}

	@Override
	public String inventoryReport() throws Exception {
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append("   ").append(this.getId()).append("\n");
		for (Host host : hosts()) {
			strBuilder.append(host.inventoryReport());
		}
		strBuilder.append("\n");
		return strBuilder.toString();
	}

	@Override
	public void revertAllVirtualMachinesToLastSnapshot() throws Exception {
		for (Host host : hosts()) {
			host.revertAllVirtualMachinesToLastSnapshot();
		}

	}

	@Override
	public List<VMachine> virtualMachine(String id) throws IOException {
		List<VMachine> virtualMachines = new ArrayList<VMachine>();
		for (Host host : hosts()) {
			VMachine virtualMachine = host.virtualMachine(id);
			if (virtualMachine != null) {
				virtualMachines.add(virtualMachine);
			}
		}
		return virtualMachines;
	}
}
